#-------------------------------------------------------------------------------
# Name:        SaveScreen
# Purpose:
#
# Author:      Pablo
#
# Created:     03/09/2013
# Copyright:   (c) Monxcleyr Productions 2013
# Licence:     GPL v3
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import pygame, config, os
from ..gui import savewidget, savedialogs

class SaveScreen():

  """Displays avaible saves and some basic information on them. Will be able to select
  a save slot to save to."""

  def __init__(self, common, sound, music, debug):
    self.common = common
    self.menuSurface = pygame.Surface(self.common.initsize)

    conf = config.Config()
    conf.read(os.path.join("resources/configs/saves.ini"))
    self.debug = debug # debug class instance
    self.sound = sound
    self.music = music
    self.common = common
    self.settings = self.common.settings
    # Custom cursor
    self.mousevisable = conf.getboolean('Graphics', 'mousevisable')
    self.cursor = conf.get('Graphics', 'mousecustom')
    self.bg = conf.getint_tuple('Graphics', 'bgcolor')
    self.alpha = conf.getint('Graphics', 'alpha')
    self.alphasurf = pygame.Surface(self.common.initsize)
    self.alphasurf.set_alpha(self.alpha)
    self.alphasurf.convert_alpha()
    if self.cursor == 'None': self.cursor = None # Reset string to key word
    if self.cursor != None:
      self.cursor = pygame.image.load(os.path.join('resources/graphics/' + self.cursor))
      self.cursor.set_colorkey((255,0,255))
    self.musicloop = conf.get('Sounds', 'music')
    if self.musicloop == 'None':
      self.musicloop = None
    self.firstdraw = True # Just a variable for checking first time through draw loop
    self.mode = 'load'
    self.selected = 0
    self.savename= ''

    font = conf.get('Graphics', 'font')
    if font == 'None': font = None
    self.fontsize = conf.getint('Graphics', 'namefontsize')
    self.namefont = pygame.font.Font(font, self.fontsize)
    self.detailfont = pygame.font.Font(font, conf.getint('Graphics', 'detailsfontsize'))
    self.fontcolor = conf.getint_tuple('Graphics', 'fontcolor')

#-------------------------------------------------------------------------------

    # Background image loading
    bgimage = conf.get('Graphics', 'bgimage')
    if bgimage == 'None': bgimage = None #just making the string 'None' into the keyword None
    if bgimage != None:
      self.bgimage = pygame.image.load(os.path.join('resources/graphics/' + bgimage)).convert_alpha()
    else:
      self.bgimage = bgimage



#-------------------------------------------------------------------------------

    # Find number of menu options
    checking = 1
    count = 1
    while checking == 1:
      if conf.has_section("Option" + str(count)) == True:
        count += 1
      else:
        checking = 0

#-------------------------------------------------------------------------------

    # Load up the menu options
    self.menu_item = []
    for i in range(1, count):
      pos = conf.getint_tuple("Option" + str(i),"position")
      button = conf.get("Option" + str(i),"button")
      buttonhover = conf.get("Option" + str(i),"buttonhover")
      clicksound = conf.get("Option" + str(i), "clicksound")
      hoversound = conf.get("Option" + str(i), "hoversound")
      mode = conf.get("Option" + str(i), "mode")
      if clicksound == 'None':
        clicksound = None
      if hoversound == 'None':
        hoversound = None
      if conf.has_option("Option" + str(i), "link") == True:
        link = conf.get("Option" + str(i), "link")
      else:
        link = ''
      self.menu_item.append(MenuItem(i, pos, button, buttonhover, clicksound, hoversound, mode, link))


#-------------------------------------------------------------------------------

    # Fine number of save widgets
    checking = 1
    count = 1
    while checking == 1:
      if conf.has_section("Save" + str(count)) == True:
        count += 1
      else:
        checking = 0


    # create widgets
    self.widgets = []
    for i in range(1,count):
      pos = conf.getint_tuple('Save' + str(i), 'position')
      widget = conf.get('Save' + str(i), 'widget')
      widgethover = conf.get('Save' + str(i), 'widgethover')
      widgetblocked = conf.get('Save' + str(i), 'widgetblocked')
      clicksound = conf.get('Save' + str(i), 'sound')
      hoversound = conf.get('Save' + str(i), 'hoversound')
      blockedsound = conf.get('Save' + str(i), 'blockedsound')
      self.widgets.append(savewidget.SaveWidget(self.menuSurface,pos, self.namefont, self.detailfont, \
        self.fontcolor, widget, widgethover, widgetblocked, clicksound, hoversound, \
        blockedsound, self.sound, self.settings,i))

#-------------------------------------------------------------------------------

    # Create dialogs
    dialogimage = conf.get('Dialogs', 'dialogimage')
    pos = conf.getint_tuple('Dialogs', 'pos')
    clicksound = conf.get('Dialogs', 'clicksound')
    hoversound = conf.get('Dialogs', 'hoversound')
    accept = conf.get('Dialogs', 'accept')
    accepthover = conf.get('Dialogs', 'accepthover')
    cancel = conf.get('Dialogs', 'cancel')
    cancelhover = conf.get('Dialogs', 'cancelhover')
    self.namedialog = savedialogs.nameDialog(self.menuSurface, dialogimage, pos, self.namefont,
    self.detailfont, self.fontcolor, clicksound, hoversound, self.common, self.sound, self.settings, \
      [accept, accepthover, cancel, cancelhover])

    self.overwritedialog = savedialogs.overwriteDialog(self.menuSurface, dialogimage, pos, self.namefont,
    self.detailfont, self.fontcolor, clicksound, hoversound, self.common, self.sound, self.settings, \
      [accept, accepthover, cancel, cancelhover])


#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------

  def draw(self, mouse, starfield, bgimage=None):

    self.mouse = mouse

    if self.firstdraw:
      mouse[1] = 0
      for widget in self.widgets:
        widget.loadSave()
##      self.widgets[4].blocked = True
      self.firstdraw = False

    self.menuSurface.fill(self.bg)


    if self.music.getCurrentLoop() != self.musicloop:
      self.music.loadQueue(self.musicloop)
      self.music.playQueue()
    if pygame.mixer.music.get_busy() == 0:
      self.music.playQueue()



    #starfield
    if self.mode is 'save' or self.mode is 'saveslot' or self.mode is 'saveoverwrite':
      starfield.draw(self.menuSurface, self.common, move=False)
    else:
      starfield.draw(self.menuSurface, self.common)

    if bgimage:
      self.menuSurface.blit(bgimage, (0,0))
      if self.alpha != 0:
        self.menuSurface.blit(self.alphasurf, (0,0))

    # Draw background stuff
    if self.bgimage != None:
      self.menuSurface.blit(self.bgimage, (0,0))


    # Check buttons to draw, hovered or normal:
    hover = self.getHover() # find a seclected button, if any
    for mitem in self.menu_item: #Get each menu item from the list
      if hover == mitem.id:
        self.menuSurface.blit(mitem.buttonhover, mitem.pos)
      else:
        self.menuSurface.blit(mitem.button, mitem.pos)


    # Draw widgets
    for widget in self.widgets:
      widget.draw(mouse, self.mode)

    # Draw dialog
    if self.mode is 'namedialog':
##      pygame.key.set_repeat(1,200) # Keys repeat
      self.namedialog.draw(mouse)

      if self.namedialog.mode == 2:
        self.mode = 'new'
        self.namedialog.reset()
      elif self.namedialog.mode == 1:
        self.savename = self.namedialog.namebox.getText()
        self.namedialog.reset()


    if self.mode is 'newoverwrite':
      self.overwritedialog.draw(mouse)
      if self.overwritedialog.mode == 2:
        self.mode = 'new'
        self.overwritedialog.reset()
      elif self.overwritedialog.mode == 1:
        self.mode = 'namedialog'


    if self.mode is 'saveoverwrite':
      self.overwritedialog.draw(mouse)
      if self.overwritedialog.mode == 2:
        self.mode = 'save'
        self.overwritedialog.reset()
      elif self.overwritedialog.mode == 1:
        self.mode = 'saveslot'



##    else:
##      pygame.key.set_repeat() # Keys no longer repeat



    # Mouse
    if self.cursor != None:
      self.menuSurface.blit(self.cursor, self.mouse[0])


    return self.menuSurface



#-------------------------------------------------------------------------------

  def getHover(self):

    """ Returns hovered option. 0 if none."""

    selected = 0

    for i in range(0, len(self.menu_item)):
      if self.menu_item[i].rect.collidepoint(self.mouse[0]):
        if not self.menu_item[i].prevhover:
          self.menu_item[i].prevhover = True
          self.sound.play(self.menu_item[i].hoversound, self.settings)
        selected = self.menu_item[i].id
      else:
        self.menu_item[i].prevhover = False

    return selected


  def getSelected(self):

    """ Returns selected option. 0 if none."""

    selected = 0
    mode = 0

    if self.mouse[1] == 2:
      pressed = True
    else:
      pressed = False
    for i in range(0, len(self.menu_item)):
      if self.menu_item[i].rect.collidepoint(self.mouse[0]) and pressed == True:
        self.sound.play(self.menu_item[i].sound, self.settings)
        selected = self.menu_item[i].id
        mode = self.menu_item[i].mode

    return selected, mode

  def reset(self):
    """Resets the menu so it operates properly next time it's used.
    Call after mode changes """
    self.firstdraw = True
    self.namedialog.reset()
    self.savename = ''
    self.selected = 0
    for widget in self.widgets:
      widget.reset()

#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------


class MenuItem:
  def __init__(self, id, pos, button, buttonhover, sound, hoversound, mode, link):

    self.id = id
    self.pos = pos
    self.button = pygame.image.load(os.path.join('resources/graphics/' + button)).convert_alpha()
    self.buttonhover = pygame.image.load(os.path.join('resources/graphics/' + buttonhover)).convert_alpha()
    #center image:
    self.pos = (pos[0] - (self.button.get_width() / 2), pos[1] - (self.button.get_height() / 2))
    self.rect = self.get_rect()
    self.sound = sound
    self.hoversound = hoversound
    self.mode = mode
    self.link = link
    self.prevhover = False

  def get_rect(self):
    return pygame.Rect(self.pos, (self.button.get_width(), self.button.get_height()))

